/******************************************************************************
 * Copyright (C) 2024 EternalChip, Inc.(Gmbh) or its affiliates.
 * 
 * All Rights Reserved.
 * 
 * @file bsp_key.c
 * 
 * @par dependencies 
 * - stdio.h
 * - stdint.h
 * 
 * @author Jack | R&D Dept. | EternalChip 立芯嵌入式
 * 
 * @brief Provide the HAL APIs of LED and corresponding opetions.
 * 
 * Processing flow:
 * 
 * call directly.
 * 
 * @version V1.0 2024-11-26
 *
 * @note 1 tab == 2 spaces!
 * 
 *****************************************************************************/

#include "bsp_led.h"

static uint32_t g_led_blink_times = 0;
static uint32_t g_led_blink_order = 0;

xQueueHandle LED_Queue = NULL;

led_status_t led_opration(led_opration_t opt)
{
  led_status_t status = LED_OK;

  if ( LED_ON == opt ) 
  {
    HAL_GPIO_WritePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin, GPIO_PIN_RESET);
  }
  else if ( LED_OFF == opt ) 
  {
    HAL_GPIO_WritePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin, GPIO_PIN_SET);
  }
  else  if ( LED_TOGGLE == opt )
  {
    HAL_GPIO_TogglePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin);
  }
  else if ( LED_BLINK == opt )
  {
    g_led_blink_times = 1;
    g_led_blink_order = 0;
    // HAL_GPIO_TogglePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin);
    // vTaskDelay(200);
    // HAL_GPIO_TogglePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin);
    // vTaskDelay(200);
  }
  else if ( LED_BLINK_10_TIMES == opt )
  {
    g_led_blink_times = 10;
    g_led_blink_order = 0;
  }

  return status;
}

void LED_Task(void *argument) 
{
  led_status_t   led_rev     = LED_OK;
  led_opration_t led_opt_val = LED_OFF;

  LED_Queue = xQueueCreate(10, sizeof(key_press_status_t));
  if ( NULL == LED_Queue ) {
    printf("LED_Queue Create Failed!\r\n");
  } else {
    printf("LED_Queue Create OK!\r\n");
  }

  for(;;)
  {
    // printf("LED_Task Running!\r\n");
    if ( pdPASS == xQueueReceive(LED_Queue, &led_opt_val, (TickType_t)100) )
    {
      printf("Queue Received led_opt_val: %d\r\n", led_opt_val);
      led_rev = led_opration(led_opt_val);
      if ( led_rev == LED_OK ) {
        printf("LED Operation OK!\r\n");
      }
    }
    osDelay(100);
  }
}

led_status_t led_callback_in_timer(void) 
{
  if ( g_led_blink_times > 0 )
  {
    if ( g_led_blink_order == 0 )
    {
      led_opration(LED_ON);
      g_led_blink_order = 1;
    }
    else
    {
      led_opration(LED_OFF);
      g_led_blink_order = 0;
      g_led_blink_times--;
    }
    // g_led_blink_order++;
  }
  return LED_OK;
}
